package com.pro.system.Controller;

import com.pro.system.Repository.UserRepository;
import com.pro.system.entity.Movie;
import com.pro.system.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("admin/users")
public class UserController {

    @Autowired
    UserRepository userRepository;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @GetMapping
    public String showMovie (Model model){
        List<User> user  = userRepository.findAll();
        model.addAttribute("user",user);
        return "web/background/users/users";
    }

    @GetMapping("intonew")
    public String intonew (Model model){
        User user = new User();
        model.addAttribute(user);
        return "web/background/users/users-new";
    }


    @PostMapping("save")
    public String save(Model model,User user){
        user.setRole("ROLE_" + user.getRole());
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        User save = userRepository.save(user);
        if(save != null){
            return "web/background/users/users-new";
        }
        else {
            return "";
        }
    }

    @PostMapping("deleteItemByCheck")
    public String deleteItemByCheck(Model model, Integer[] getvalues){
        for(int i=0; i<getvalues.length;++i){
            userRepository.deleteById(getvalues[i]);
        }
        return "redirect:/admin/users";
    }

    @PostMapping("research")
    public String research(Model model,@RequestParam String ByNameLike){
        List<User> ByNameLikes = userRepository.findByNameLike(ByNameLike);
        model.addAttribute("user",ByNameLikes);
        return  "web/background/users/users";
    }
}
